<?php

/**
 * Handles the edit post shortcode
 *
 * @return string generated form by the plugin
 */
function wpuf_edit_post_shorcode() {

    ob_start();

    if ( is_user_logged_in() ) {
        wpuf_edit_post();
    } else {
        printf( __( "This page is currently restricted. Please log out and in again.", 'wpuf' ), wp_loginout( '', false ) );
    }

    $content =  ob_get_contents();
    ob_end_clean();

    return $content;
}

add_shortcode( 'wpuf_edit', 'wpuf_edit_post_shorcode' );

/**
 * Main edit post form
 *
 * @global type $wpdb
 * @global type $userdata
 */
function wpuf_edit_post() {
    global $wpdb, $userdata;

    $post_id = wpuf_is_valid_int( $_GET['pid'] );

    if ( $post_id ) {

        if ( get_option( 'wpuf_can_edit_post' ) == 'yes' ) {

            //delete post attachment
            if ( isset( $_REQUEST['action'] ) && $_REQUEST['action'] == "del" ) {
                check_admin_referer( 'wpuf_attach_del' );
                $attach_id = intval( $_REQUEST['attach_id'] );

                if ( $attach_id ) {
                    wp_delete_attachment( $attach_id );
                }
            }

            //validate new post submission
            $nonce = $_REQUEST['_wpnonce'];
            if ( isset( $_POST['wpuf_edit_post_submit'] ) && wp_verify_nonce( $nonce, 'wpuf-edit-post' ) ) {
                wpuf_validate_post_edit_submit();
            }

            $curpost = get_post( $post_id, 'OBJECT' );

            if ( $curpost ) {
                if ( intval( $userdata->ID ) != intval( $curpost->post_author ) ) {
                    wp_redirect( site_url() );
                    exit;
                }

                wpuf_edit_show_form( $curpost );
            } else {
                $error = __( 'Invalid post', 'wpuf' );
            }
        } else {
            $error = __( 'Post Editing is disabled', 'wpuf' );
        }
    } else {
        $error = __( 'Invalid post id', 'wpuf' );
    }

    if ( isset( $error ) ) {
        echo '<div class="error">Error: ' . $error . '</div>';
    }
}

function wpuf_edit_show_form( $post ) {
    $post_tags = wp_get_post_tags( $post->ID );
    $tagsarray = array();
    foreach ($post_tags as $tag) {
        $tagsarray[] = $tag->name;
    }
    $tagslist = implode( ', ', $tagsarray );
    $categories = get_the_category( $post->ID );
    ?>
    <form name="wpuf_edit_post_form" id="wpuf_edit_post_form" action="" enctype="multipart/form-data" method="POST" style="float:left;">
        <?php wp_nonce_field( 'wpuf-edit-post' ) ?>
        <ul class="wpuf-post-form">
<strong>Guidelines for editing documents:</strong><br><br>
1. Tick 'Enable reader reviews' if you would like to receive reviews and feedback.<br><br>
2. Always start off writing using the <b>HTML tab</b> above the writing box. Do <b>not</b> simply copy and paste text here from another window. Often text will include embedded (invisible) codes that may adversely affect the look of your document. Best practice is to use Notepad and copy any text there. Then you can re-copy it from Notepad and paste it below. This will remove any unwanted formatting. To check the appearance of your document when finished click on the <b>Visual tab</b>. <br><br> 



            <?php do_action( 'wpuf_add_post_form_top', $post_type ); //plugin hook  ?>
            <?php wpuf_build_custom_field_form( 'top', true, $post->ID ); ?>

            <li>
                <label for="new-post-title">
                    <?php echo get_option( 'wpuf_title_label' ); ?> <span class="required">*</span>
                </label>
                <input type="text" name="wpuf_post_title" id="new-post-title" minlength="2" value="<?php echo esc_html( $post->post_title ); ?>">
                <div class="clear"></div>
            </li>

            <?php 
						 $wpuf_userrole = wpuf_role();

						if ( get_option( 'wpuf_allow_choose_cat' ) == 'yes' ) {
							if ( !in_category(6, $post->ID) && dk_get_e_member() != 'Bookshop' && dk_get_e_member() != "Book Club" ) {
				?>
                <li>
                    <label for="new-post-cat">
                        <?php echo get_option( 'wpuf_cat_label' ); ?>
                    </label>
                    <div style="float:left; min-width: 300px;">
                        <div id="catlvl0">
                    <?php
                    $select = array();
						  $checkbox = array();
                    foreach ( get_the_category($post->ID) as $category ) {
								if ( $category->parent != 0 ) {
									$select[$category->parent][] = $category->cat_ID;
								} else {
									$checkbox[] = $category->cat_ID;
								}
						  }

							$exclude = get_option( 'wpuf_exclude_cat' );
							if ( $wpuf_userrole == 'member' ) $exclude .= ',42,7';

							$author_book_chk = false;
							$args=array('hierarchical' => 0, 'hide_empty' => 0, 'orderby' => 'name', 'exclude' => $exclude.',6');
							foreach ( get_categories($args) as $category ) {
								if ( $category->category_parent == 0 ) {
									$checked = '';
									if ( in_array($category->cat_ID, $checkbox) ) {
										$checked = 'checked="checked"';

										if ( $category->cat_ID == 7 ) $author_book_chk = true;
									}

									if ( $category->cat_ID == 6 ) {
										echo $category->cat_name; ?><input type="checkbox" class="cat" name="category[]" value="<?php echo $category->cat_ID; ?>" <?php echo $checked; ?> /><br />
							<?php } else {
									echo $category->cat_name; ?><input type="radio" class="cat" name="category[]" value="<?php echo $category->cat_ID; ?>" <?php echo $checked; ?> /><br />
							<?php }
									switch ( $category->cat_ID ) {
										case 7:
											wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&show_count=0&title_li=&name=category[]&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&exclude='.$exclude.'&child_of='.$category->cat_ID.'&selected='.$select[$category->cat_ID][0]);
											echo '<br />';
											wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&show_count=0&title_li=&name=category[]&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&exclude='.$exclude.'&child_of='.$category->cat_ID.'&selected='.$select[$category->cat_ID][1]);
											echo '<br />';
											wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&show_count=0&title_li=&name=category[]&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&exclude='.$exclude.'&child_of='.$category->cat_ID.'&selected='.$select[$category->cat_ID][2]);
											echo '<br />';
											break;
										case 37:
										case 39:
											wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=id&show_count=0&title_li=&name=category[]&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&exclude='.$exclude.'&child_of='.$category->cat_ID.'&selected='.$select[$category->cat_ID][0]);
											echo '<br />';
											break;
									}
								}
							}
                    ?>
                        </div>
                    </div>
                    <div class="clear"></div>
                    <p class="description"><?php echo stripslashes( get_option( 'wpuf_cat_help' ) ); ?></p>
                    <div class="clear"></div>
                </li>
            <?php		}
						 }

						if ( $wpuf_userrole == 'member' || $wpuf_userrole == 'author' ) {
							if ( !$author_book_chk ) $style = 'style="display:none;"';

							$amazon_kindle = get_post_meta($post->ID, 'amazon_kindle', true);
							$ibookstore = get_post_meta($post->ID, 'ibookstore', true);
							$nook = get_post_meta($post->ID, 'nook', true);
							$waterstones = get_post_meta($post->ID, 'waterstones', true);
							$partner = get_post_meta($post->ID, 'partner', true);
						?>
                    <li id="book_url" <?php echo $style; ?>>
								<div align="left">
								<label>Enter your book's URL (include 'http://www.'):</label><div class="clear"></div>
                        Kindle<br /><input type="text" name="amazon_kindle" value="<?=$amazon_kindle?>" /><br />
                        iBookstore<br /><input type="text" name="ibookstore" value="<?=$ibookstore?>" /><br />
                        Nook<br /><input type="text" name="nook" value="<?=$nook?>" /><br />
                        Waterstones<br /><input type="text" name="waterstones" value="<?=$waterstones?>" /><br />
                        Referral or discount reseller<br /><input type="text" name="partner" value="<?=$partner?>" /><br />
								</div>
                        <div class="clear"></div>
                    </li>
							<?php
						}

						$featured = get_post_meta($post->ID, 'synch_featured', true);
?>
                  <input type="hidden" name="synch_featured" id="synch_featured" value="<?php echo ($featured == 'on' ? 1 : 0) ?>" />

<?php
/*
						if ( $wpuf_userrole != 'member' ) {
							$featured = get_post_meta($post->ID, 'synch_slider', true);
							$checked = ( $featured == 'on' ? 'checked="checked"' : '' );
				?>
                <li>
                    <input type="checkbox" name="synch_slider" value="1" <?php echo $checked; ?> /><label>Enable book cover</label>
                    <div class="clear"></div>
                </li>
				<?php
						}
*/
						$featured = get_post_meta($post->ID, 'wpcr_enable', true);
						$checked = ( $featured == '1' ? 'checked="checked"' : '' );
				?>
                <li>
                    <input type="checkbox" name="wpcr_enable" value="1" <?php echo $checked; ?> /><label>Enable reader reviews</label>
                    <div class="clear"></div>
                </li>

            <?php do_action( 'wpuf_add_post_form_description', $post_type ); ?>
            <?php wpuf_build_custom_field_form( 'description', true, $post->ID ); ?>

            <li>
                <label for="new-post-desc">
                    <?php echo get_option( 'wpuf_desc_label' ); ?> <span class="required">*</span>
                </label><br><br>
<?php if(in_array('Author' ,dk_get_e_member_arr()) || in_array('Author' ,dk_get_e_member_arr())):?>        
If you wish to add an author photo or book cover use <b>Upload/Insert</b> below.<br><br>
For the best results author photos should be 200x298px and for book covers 200x300px. You can edit your image where indicated. Once you have uploaded your image to the system please contact us at authors@wonderbookland.com so we can enable the image.<br><br> 
<?php endif;?>
                <div style="float:left;">
                    <?php if ( get_option( 'wpuf_editor_type' ) == 'rich' ) { ?>
                        <?php wp_editor( $post->post_content, 'new-post-desc', array('textarea_name' => 'wpuf_post_content', 'teeny' => true, 'textarea_rows' => 20) ); ?>
                    <?php } else { ?>
                        <textarea name="wpuf_post_content" id="new-post-desc" cols="60" rows="20"><?php echo esc_textarea( $post->post_content ); ?></textarea>
                    <?php } ?>
                </div>
                <div class="clear"></div>
            </li>

            <?php do_action( 'wpuf_add_post_form_after_description', $post_type ); ?>
            <?php wpuf_build_custom_field_form( 'tag', true, $post->ID ); ?>

            <?php if ( get_option( 'wpuf_allow_tags' ) == 'yes' ) { ?>
                <li>
                    <label for="new-post-tags">
                        <?php echo get_option( 'wpuf_tag_label' ); ?>
                    </label>
                    <input type="text" name="wpuf_post_tags" id="new-post-tags" value="<?php echo $tagslist; ?>">
                    <div class="clear"></div>
                </li>
            <?php } ?>

            <?php wpuf_attachment_fields(); ?>
            
            <?php do_action( 'wpuf_add_post_form_tags', $post_type ); ?>
            <?php wpuf_build_custom_field_form( 'bottom', true, $post->ID ); ?>

            <li style="text-align:left;">
                <input class="wpuf_submit" type="submit" name="wpuf_edit_post_submit" value="<?php _e( 'Update', 'wpuf' ); ?>">
                <input type="hidden" name="wpuf_edit_post_submit" value="yes" />
                <input type="hidden" name="post_id" value="<?php echo $post->ID; ?>">
            </li>
        </ul>
    </form>
    <div class="wpuf-edit-attachment">
        <?php //wpuf_edit_attachment( $post->ID ); ?>
    </div>
<script type="text/javascript">
jQuery(document).ready(function($){
	$('select[name^=category]').attr('disabled', 'disabled');
	$('input:radio[name^=category]:checked').each(function(i) {
		$('select.incat'+$(this).val()).removeAttr('disabled');
	});

	$('input:radio[name^=category]').live('change', function() {
		var val = $(this).val();

		$('select[name^=category]').attr('disabled', 'disabled').val(-1);

		if ( val == 7 ) {
			$('#book_url').css('display', '');
		} else {
			$('#book_url').css('display', 'none');
		}

		$('select.incat'+val).removeAttr('disabled');
	});
});
</script>    
    <?php
}

function wpuf_validate_post_edit_submit() {
    global $userdata;

    $errors = array();

    $title = trim( $_POST['wpuf_post_title'] );
    $content = trim( $_POST['wpuf_post_content'] );
    $tags = wpuf_clean_tags( $_POST['wpuf_post_tags'] );
    $cat = $_POST['category'];

    //if there is some attachement, validate them
    if ( !empty( $_FILES['wpuf_post_attachments'] ) ) {
        $errors = wpuf_check_upload();
    }

    if ( empty( $title ) ) {
        $errors[] = "Empty post title";
    } else {
        $title = trim( strip_tags( $title ) );
    }

    if ( empty( $content ) ) {
        $errors[] = "Empty post content";
    } else {
        $content = trim( $content );
    }

    if ( !empty( $tags ) ) {
        $tags = explode( ',', $tags );
    }

    //process the custom fields
    $custom_fields = array();

    $fields = wpuf_get_custom_fields();
    if ( is_array( $fields ) ) {

        foreach ($fields as $cf) {
            if ( array_key_exists( $cf['field'], $_POST ) ) {

                $temp = trim( strip_tags( $_POST[$cf['field']] ) );
                //var_dump($temp, $cf);

                if ( ( $cf['type'] == 'yes' ) && !$temp ) {
                    $errors[] = __( "{$cf['label']} is missing", 'wpuf' );
                } else {
                    $custom_fields[$cf['field']] = $temp;
                }
            } //array_key_exists
        } //foreach
    } //is_array

    do_action( 'wpuf_edit_post_validation', intval( $_POST['post_id'] ) );

    if ( !$errors ) {
        $post_update = array(
            'ID' => trim( $_POST['post_id'] ),
            'post_title' => $title,
            'post_content' => $content,
            'post_category' => $cat,
            'tags_input' => $tags
        );

        //plugin API to extend the functionality
        $my_post = apply_filters( 'wpuf_edit_post_args', $my_post );

        $post_id = wp_update_post( $post_update );

        if ( $post_id ) {
            echo '<div class="success">Post updated succesfully.</div>';

            //upload attachment to the post
            wpuf_upload_attachment( $post_id );

            //add the custom fields
            if ( $custom_fields ) {
                foreach ($custom_fields as $key => $val) {
                    update_post_meta( $post_id, $key, $val, false );
                }
            }

				update_post_meta($post_id, 'wpcr_enable', (int) isset($_POST['wpcr_enable']));
				update_post_meta($post_id, 'synch_featured', ( ( (int) isset($_POST['synch_featured']) ) ? 'on' : 'off' ));
//				update_post_meta($post_id, 'synch_slider', ( ( (int) $_POST['synch_slider'] ) ? 'on' : 'off' ));

				if ( in_array(7, $cat) ) {
					update_post_meta($post_id, 'amazon_kindle', $_POST['amazon_kindle']);
					update_post_meta($post_id, 'ibookstore', $_POST['ibookstore']);
					update_post_meta($post_id, 'nook', $_POST['nook']);
					update_post_meta($post_id, 'waterstones', $_POST['waterstones']);
					update_post_meta($post_id, 'partner', $_POST['partner']);
				} else {
					update_post_meta($post_id, 'amazon_kindle', '');
					update_post_meta($post_id, 'ibookstore', '');
					update_post_meta($post_id, 'nook', '');
					update_post_meta($post_id, 'waterstones', '');
					update_post_meta($post_id, 'partner', '');
				}

            do_action( 'wpuf_edit_post_after_update', $post_id );
        }
    } else {
        echo wpuf_error_msg( $errors );
    }
}